package falcon.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public final class TextFile {
	
	public static boolean exists(String path) {
		return new File(path).exists();
	}
	
	public static long getLastMtime(String path) {
		File f = new File(path);
		if (!f.exists()) {
			return 0L;
		}
		return f.lastModified();
	}

	public static int write(String path, String text, boolean append) {
		int errno = Errno.SUCCESS;
		try {
			BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, append), Global.DEFAULT_CHARSET));
			try {
				br.write(text);
				br.flush();
			} finally {
				br.close();
			}
		} catch (Exception e) {
			errno = Errno.COM_WRITE_FILE_ERROR;
			Log.log(e, "append=%s;path=%s", append, path);
		}
		return errno;
	}
	
	public static int writeLines(String path, String[] lines, boolean append) {
		return Errno.SUCCESS;
	}
	
	public static String read(String path) {
		return null;
	}
	
	public static String[] readLines(String path) {
		String[] lines = null;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(path));
			ArrayList<String> list = new ArrayList<String>(256);
			try {
				String line = null;
				while ((line = br.readLine()) != null) {
					list.add(line);
				}
			} finally {
				if (br != null) {
					br.close();
				}
			}
			lines = new String[list.size()];
			list.toArray(lines);
		} catch (FileNotFoundException e) {
			lines = null;
			Log.log(e, "path not found;path=%s", path);
		} catch (IOException e) {
			lines = null;
			Log.log(e, "read file error;path=%s", path);
		}
		return lines;
	}
}
